package cn.lxm.cas.client2.controller;

import cn.lxm.cas.client2.config.CasProperties;
import com.google.gson.Gson;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@Controller
public class HomeController {

    @RequestMapping(value = {"/", "/index"}, method = RequestMethod.GET)
    public String index(ModelMap modelMap, HttpSession session) {
        modelMap.addAttribute("msg", "welcome to spring-boot-cas-client!");
        modelMap.addAttribute("sessionId", session.getId());
        return "index";
    }

    @GetMapping(value = "/user")
    @PreAuthorize("hasRole('ROLE_USER')")
    public String user(ModelMap modelMap) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        modelMap.addAttribute("user", user);
        return "user";
    }


    //    @ResponseBody
    @GetMapping("/hello")
    @PreAuthorize("hasAnyRole('ROLE_USER')")
    public void test(HttpServletRequest reques, HttpServletResponse response) {
//        JSONObject jsonObject = new JSONObject();
//        makeResult(jsonObject);
//
//        JSONPObject jpo = new JSONPObject(callbackJsonp, jsonObject);
//
//        CasProperties properties = new CasProperties();
//        properties.setAppLoginUrl("12313133");
//        properties.setCasServerLogoutUrl("33333");
//        String re = "success_jsonpCallback(" + new Gson().toJson(properties) + ")";
//        return re;

//        try {
////            this.loggerer.info("进入首页，查询参数str=" + str);
//            Map map = new HashMap<>();
//            map.put("dateli", "2222");
//            String jj = "success_jsonpCallback(" + new Gson().toJson(map) + ")";
////            this.loggererger.info("返回结果=" + jj.toString());
//            InputStream is = new ByteArrayInputStream(
//                    jj.toString().getBytes("UTF-8"));
//            // copy it to response's OutputStream
//            IOUtils.copy(is, response.getOutputStream());
//            response.flushBuffer();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return;
    }
}